import React, { Component } from "react";
import { SafeAreaView, Text, View, StyleSheet, TouchableOpacity, Image, DeviceEventEmitter, ScrollView, Dimensions } from 'react-native';
import Constant from '../../utils/Constant'//全局变量
import { getImgUrl, getPerm } from '../../utils/ComFunction';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import { PermissionType } from "../../utils/Enum";
import AsyncImage from "../../components/image/AsyncImage";

const screenW = Dimensions.get('window').width;


const itemWidth = 52

let itemSpace = ((screenW - 15 * 2 - 16 * 2 - 4 * itemWidth) / 3)

export default class MyCenterPage extends Component {

    constructor(props) {
        super(props);
        let employeeManagerPerm = getPerm(PermissionType.Permission_EnableManageEmployee)
        let dutyManagerPerm = getPerm(PermissionType.Permission_EnableManageDuty)
        let EditCompanyrPerm = getPerm(PermissionType.Permission_EnableEditCompanyInfo)
        this.state = {
            isExternalCarEntryUser: Constant.userInfo.isExternalCarEntryUser || 0, // 是否是外部车辆录入用户
            employeeManagerPerm,
            dutyManagerPerm,
            EditCompanyrPerm,
            effectiveDate: '',
            memberText: '',
            memberIcon: null,
            isShowVip: false,
            headImg: '',
            fullname: ''
        };
    }

    componentDidMount() {
        let that = this
        this.updateUserInfo = DeviceEventEmitter.addListener('commonEvent', e => {
            if (e.type == 'updateUserInfo') {
                if (e.face) {
                    that.setState({
                        headImg: getImgUrl(e.face)
                    })
                }
                if (e.fullname) {
                    that.setState({
                        fullname: e.fullname
                    })
                }
            }
        });

        this.focusListener = this.props.navigation.addListener('focus', () => {
           
            DeviceEventEmitter.emit('homeListener', {isInHome:false,index:4});
        });

        this.backHome = DeviceEventEmitter.addListener('backHome', (result) => {
            if (result && result.index == 4) {
                this.props.navigation.navigate('WorkCenterPage')
            }
        })

        this.setState({
            headImg: getImgUrl(Constant.userInfo.face),
            fullname: Constant.userInfo.fullname
        })

        this.getMemberInfo()
    }

    componentWillUnmount() {
        if (this.updateUserInfo) {
            this.updateUserInfo.remove();
        }

        if(this.backHome){
            this.backHome.remove();
        }
    }

    render() {
        const navigation = this.props.navigation;
        return (
            <View
                style={styles.container}>
                <Header navigation={navigation} Title={'我的'} hideSepLine={true} bgColor={'#f9f9f9'}></Header>

                <ScrollView>
                    <TouchableOpacity
                        style={styles.userInfo}
                        activeOpacity={1.0}
                        onPress={() => { navigation.navigate('UserInfoPage') }}>
                        <AsyncImage
                            defaultSource={require('source/image/userIcon.png')}
                            source={{ uri: this.state.headImg }}
                            style={styles.avatar}
                        />

                        <View style={styles.userTextContainer}>
                            <Text style={styles.username}>{this.state.fullname}</Text>
                            <Text style={styles.userRole}>{Constant.userInfo.roleName}</Text>
                        </View>
                        <Image style={styles.arrowImg} source={require('source/image/comm/icon_tree_arrow.png')} />
                    </TouchableOpacity>

                    <View style={{ paddingHorizontal: 15 }}>
                        {this.state.isShowVip && Constant.userInfo.isFranchisee != 1 ?
                            <TouchableOpacity
                                style={styles.memberInfo}
                                activeOpacity={1.0}
                                onPress={() => { navigation.navigate('UserInfoPage') }}
                            >
                                <Image
                                    source={this.state.memberIcon}
                                    style={styles.vipIcon}
                                />
                                <Text style={styles.memberText}>{this.state.memberText}</Text>
                            </TouchableOpacity>
                            :
                            null
                        }
                    </View>

                    <View style={styles.menuContainer}>

                        <TouchableOpacity
                            activeOpacity={0.8}
                            style={styles.menuItem}
                            onPress={() => {
                                navigation.navigate('FeedBack')
                            }}>
                            <Text style={styles.menuText}>意见反馈</Text>
                            <Image style={styles.arrowImg} source={require('source/image/comm/icon_tree_arrow.png')} />
                        </TouchableOpacity>
                        <TouchableOpacity
                            activeOpacity={0.8}
                            style={[styles.menuItem, { borderBottomWidth: 0 }]}
                            onPress={() => {
                                navigation.navigate('ContactUs')
                            }}>
                            <Text style={styles.menuText}>平台客服</Text>
                            <Image style={styles.arrowImg} source={require('source/image/comm/icon_tree_arrow.png')} />
                        </TouchableOpacity>
                    </View>

                    <View style={styles.menuContainer}>


                        <TouchableOpacity
                            activeOpacity={0.8}
                            style={[styles.menuItem, { borderBottomWidth: 0 }]}
                            onPress={() => {
                                navigation.navigate('Setting')
                            }}>
                            <Text style={styles.menuText}>设置</Text>
                            <Image style={styles.arrowImg} source={require('source/image/comm/icon_tree_arrow.png')} />
                        </TouchableOpacity>
                    </View>

                    {this.state.isExternalCarEntryUser == 0 && (
                        <View style={styles.serviceBox}>
                            <View style={styles.serviceTitleBox}><Text style={styles.titleText}>公司管理</Text></View>
                            <View style={styles.serviceBottomBox}>
                                {
                                    this.state.employeeManagerPerm ?
                                        <TouchableOpacity
                                            activeOpacity={0.8}
                                            style={[styles.toolItemBox, { marginRight: itemSpace }]}
                                            onPress={() => {
                                                navigation.navigate('CompanyEmployee')
                                            }}
                                        >
                                            <Image style={styles.toolItemImg} source={require('source/image/workCenter/staff_icon.png')} />
                                            <Text style={styles.toolItemText}>员工管理</Text>
                                        </TouchableOpacity>
                                        :
                                        null
                                }

                                {
                                    this.state.dutyManagerPerm ?
                                        <TouchableOpacity
                                            activeOpacity={0.8}
                                            style={[styles.toolItemBox, { marginRight: itemSpace }]}
                                            onPress={() => {
                                                navigation.navigate('DutyManager')
                                            }}
                                        >
                                            <Image style={styles.toolItemImg} source={require('source/image/workCenter/role_icon.png')} />
                                            <Text style={styles.toolItemText}>职务管理</Text>
                                        </TouchableOpacity>
                                        :
                                        null
                                }


                                <TouchableOpacity
                                    activeOpacity={0.8}
                                    style={[styles.toolItemBox, { marginRight: itemSpace }]}
                                    onPress={() => {
                                        navigation.navigate('FundAccountPage')
                                    }}
                                >
                                    <Image style={styles.toolItemImg} source={require('source/image/workCenter/cash_account_icon.png')} />
                                    <Text style={styles.toolItemText}>资金账户</Text>
                                </TouchableOpacity>
                                {
                                    this.state.EditCompanyrPerm ?
                                        <TouchableOpacity
                                            activeOpacity={0.8}
                                            style={styles.toolItemBox}
                                            onPress={() => {
                                                navigation.navigate('StoreInfo')
                                            }}
                                        >
                                            <Image style={styles.toolItemImg} source={require('source/image/workCenter/company_icon.png')} />
                                            <Text style={styles.toolItemText}>企业设置</Text>
                                        </TouchableOpacity>
                                        :
                                        null
                                }

                            </View>
                        </View>
                    )}

                </ScrollView>

            </View>
        );
    }

    getMemberInfo() {
        HttpUtils.getRequest(HttpUrls.getMerchantMember, { merchantId: Constant.userInfo.merchantId })
            .then((result) => {
                let code = result.code
                if (code == 0) {
                    let data = result.data

                    let memberClass = data.memberClass
                    if (data.expireTime && data.expireTime > 0) {
                        if (memberClass == 20) {
                            this.setState({
                                memberIcon: require('source/image/company/sc_member_class_honest_member_label.png')
                            })

                        } else if (memberClass == 30) {
                            this.setState({
                                memberIcon: require('source/image/company/sc_member_class_honest_member_label.png')
                            })

                        } else if (memberClass == 40) {
                            this.setState({
                                memberIcon: require('source/image/company/sc_member_class_strictly_member_label.png')
                            })

                        } else {
                            this.setState({
                                memberIcon: require('source/image/company/sc_member_class_alliance_member_badge.png')
                            })

                        }
                        this.setState({
                            memberText: '有效期至' + data.effectiveDate,
                            isShowVip: true
                        })
                    } else if (data.expireTime && data.expireTime <= 0) {
                        let vipstr = ''
                        if (memberClass == 20) {

                            vipstr = '联盟会员'

                        } else if (memberClass == 30) {
                            vipstr = '诚信会员'

                        } else if (memberClass == 40) {
                            vipstr = '严选会员'

                        } else {
                            vipstr = '会员'

                        }
                        this.setState({
                            memberText: vipstr + '已过期',
                            memberIcon: require('source/image/company/sc_member_class_alliance_member_badge.png'),
                            isShowVip: true
                        })
                    } else {
                        this.setState({
                            isShowVip: false
                        })
                    }

                }
            })
            .catch((error) => {

            });
    }

};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f9f9f9',
    },
    topContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 15,
        width: '100%',
        backgroundColor: '#ffffff'
    },
    topText: {
        fontSize: 20,
        color: '#333333'
    },
    userInfo: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 15,
        backgroundColor: '#FFFFFF',
        marginLeft: 15,
        marginRight: 15,
        borderRadius: 6,
    },
    avatar: {
        width: 60,
        height: 60,
        borderRadius: 30,
    },
    userTextContainer: {
        flex: 1,
        marginLeft: 15,
    },
    username: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333333'
    },
    userRole: {
        fontSize: 14,
        color: '#666666',
        marginTop: 10,
    },
    memberInfo: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingBottom: 10,
        paddingTop: 0,
        borderBottomLeftRadius: 6,
        borderBottomRightRadius: 6,
        backgroundColor: '#FFFFFF',

    },
    vipIcon: {
        width: 80,
        height: 30,
        marginRight: 10,
        marginLeft: 10,
        resizeMode: 'contain'
    },
    memberText: {
        fontSize: 14,
        color: '#333333',
    },
    menuContainer: {
        backgroundColor: '#fff',
        borderRadius: 6,
        marginTop: 10,
        marginLeft: 15,
        marginRight: 15
    },
    menuItem: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 15,
        borderBottomWidth: 0.5,
        borderBottomColor: '#EEEEEE',
    },
    menuText: {
        flex: 1,
        fontSize: 16,
        color: '#222222'
    },
    arrowImg: {
        width: 15,
        height: 15
    },

    serviceBox: {
        marginTop: 10,
        marginBottom: 12,
        marginHorizontal: 15,
        paddingVertical: 14,
        backgroundColor: '#fff',
        borderRadius: 6,
        flexDirection: 'column'
    },
    serviceTitleBox: {
        height: 20,
        marginLeft: 12,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between'
    },
    titleText: {
        fontSize: 16,
        color: '#333333',
        fontWeight: '500',
        textAlignVertical: 'center'
    },
    serviceBottomBox: {
        paddingHorizontal: 16,
        marginTop: 14,
        flexDirection: 'row',
    },
    toolItemBox: {
        width: itemWidth,
        flexDirection: 'column',
        alignItems: 'center',
    },
    toolItemImg: {
        width: 32,
        height: 32
    },
    toolItemText: {
        color: '#333333',
        fontSize: 12,
        marginTop: 9
    },

});